const http = require('http');
const fs = require('fs');
const url = require('url');
const querystring = require('querystring');


let server = http.createServer();

let datas = [
    {name: 'jjjj', content: '在海边说', time: '2017-12-12-12-12-12'},
    {name: 'aaaa', content: '在海边说', time: '2018-12-12-12-12-12'},
    {name: 'wwww', content: '在海边说', time: '2019-12-12-12-12-12'},
    {name: 'yyyy', content: '在海边说', time: '2027-12-12-12-12-12'},
    {name: 'iiii', content: '在海边说', time: '2427-12-12-12-12-12'},
];

server.on('request', (req, res) => {
    let data = '';
    if (req.url === '/') {
        fs.readFile('./view/留言本.html' , function (err, val) {
            if (err) res.end('404');
            res.setHeader('Content-Type', 'text/html;charset=utf-8');
            data = val.toString();
            let html = '';
            datas.forEach(item => {
               html += `<li>
                        ${item.name + item.content}:
                        ${item.time}
                        </li>`
            });

            data = data.replace('^_^', html)
            res.write(data);
            res.end();
        })
    } else if (req.url === '/add') {
        fs.readFile('./view/添加留言.html' , function (err, val) {
            if (err) res.end('404');
            res.setHeader('Content-Type', 'text/html;charset=utf-8');
            data = val.toString();
            res.write(data);
            res.end();
        })
    } else if (req.url.indexOf('/public') !== -1) {
        fs.readFile('.' + req.url , function (err, val) {
            if (err) res.end('404');
            data = val.toString();
            res.write(data);
            res.end();
        })
    } else if (req.url.indexOf('/doadd') !== -1) {
        if (req.method === 'GET') {
            let obj = url.parse(req.url, true).query;
            datas.push({
                name: obj.name,
                content: obj.content,
                time: new Date()
            });

        } else if (req.method === 'POST') {
            let postData = '';
            req.on('data', function (val) {
                postData +=val
            });
            req.on('end', function () {
                postData = querystring.parse(postData);
                datas.push({
                    name: postData.name,
                    content: postData.content,
                    time: new Date()
                });
            })
        }
        // 要实现重定向，必须写上statusCode 301和setHeader
        res.statusCode = 301;
        res.setHeader('Location', 'http://localhost:8080/');
        res.end();
    }
    else {
            fs.readFile('./view/404.html' , function (err, val) {
            if (err) res.end('404');
            res.setHeader('Content-Type', 'text/html;charset=utf-8');
            data = val.toString();
            res.write(data);
            res.end();

            })
    }
});

server.listen(8080, function () {
    console.log('服务器启动，端口为8080');
});